<?php

namespace LhpAmis\Traits;

use think\facade\Cache;
use think\facade\Env;
trait AmisAdminTrait
{

    /**
     * 当前模型
     * @Model
     * @var object
     */
    protected $model;


    /**
     * 模板布局, false取消
     * @var string|bool
     */
    protected $layout = 'view/index';


    protected function cacheMethodWhere($where)
    {
        Cache::store('redis')->hset('product.listing.search', session('admin.id'), json_encode($where));
    }

    /**
     * 模板变量赋值
     * @param string|array $name 模板变量
     * @param mixed $value 变量值
     * @return mixed
     */
    public function assign($name, $value = null)
    {
        return $this->app->view->assign($name, $value);
    }


    /**
     * 解析和获取模板内容 用于输出
     * @param array $vars
     * @return mixed
     */
    public function fetch($vars = [])
    {
        if ($this->request->isJson()) {
            return $this->data($vars);
        }
        $this->layout = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR . 'index.html';

        $assign['amisJSON'] = amis()->Page()->className('m:overflow-auto pb-48')->body($vars);
        $assign['extend_css_list'] = Env::get('extend_css_list');
        $assign['extend_js_list'] = Env::get('extend_js_list');

        return $this->app->view->fetch($this->layout, $assign);
    }

    /**
     * 重写验证规则
     * @param array $data
     * @param array|string $validate
     * @param array $message
     * @param bool $batch
     * @return array|bool|string|true
     */
    public function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        try {
            parent::validate($data, $validate, $message, $batch);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return true;
    }


    /**
     * 递归处理布尔值
     * @param mixed $data
     * @return mixed
     */
    protected function convertBooleansToNumbers(&$data)
    {
        if (is_array($data)) {
            foreach ($data as &$value) {
                $this->convertBooleansToNumbers($value);
            }
        } elseif (is_object($data)) {
            foreach ($data as &$value) {
                $this->convertBooleansToNumbers($value);
            }
        } elseif (is_bool($data)) {
            $data = $data ? 1 : 0;
        }
        return $data;
    }


    public function modify()
    {
        // 获取原始的 JSON 数据
        $jsonData = file_get_contents('php://input');

        // 解析 JSON 数据
        $rows = json_decode($jsonData, true);

        // 调用自定义的函数处理布尔值
        if (is_array($rows)) {
            $this->convertBooleansToNumbers($rows);
        }

        // 继续处理 $rows
        $rows = $this->convertBooleansToNumbers($rows);

        if (isset($rows['rowsDiff'])) {
            $ids = explode(',', $rows['ids']);

            // 遍历每个记录进行验证和更新
            foreach ($rows['rowsDiff'] as $index => $row) {
                // 更新记录
                try {
                    $data = $this->model->where('id', $ids[$index])->find();
                    unset($row['create_time']);
                    unset($row['update_time']);
                    $data->save($row);
                } catch (\Exception $e) {
                    $this->error("第" . ($index + 1) . "个记录更新失败: " . $e->getMessage());
                }
            }
        } else if (isset($rows['id'])) {
            $data = $this->model->where('id', $rows['id'])->find();
            unset($rows['create_time']);
            unset($rows['update_time']);
            $data->save($rows);
        }

        $this->success();
    }
}